#-*- coding:UTF-8 -*-
"""
Google App Engine (GAE) 分页类
Usage: 
    query = User.gql('order by lastname')
    pager = Paginator(query,url="/userlist/",pagesize=5)
    results,pager = pager.fetch(offset)
	
"""
import logging

class Paginator(object):
  def __init__(self,query=None,pagesize=5,url=None):
    self.query = query
    self.pagesize = pagesize
    if not url.endswith('/'):
      self.url = url + '/'
    else:
      self.url = url
    
  def fetch(self,offset):
    if offset < 0:
      offset = 0
    results =self.query.fetch(100,offset)
    logging.info("offset="+str(offset))
    output = self.create_links(offset,len(results))
    logging.info("output="+output+"  len="+str(len(results)))
    return {'results':results[:self.pagesize],'output':output}
  
  def create_links(self,offset,count):
    num_links = 5 #count/self.pagesize -
    if count % self.pagesize == 0 :
      num_pages = count / self.pagesize
    else:
      num_pages = count / self.pagesize + 1 

    cur_page = offset
    start_page = 1
    end_page = num_pages 

    if cur_page < start_page:
      cur_page = start_page

    if cur_page > end_page:
      cur_page = end_page

    """ 
    end_page = cur_page + num_links

    if cur_page - num_links >0:
      start_page = cur_page - num_links + 1
    if num_pages < num_links:
      end_page = cur_page + num_pages 
    """
    logging.info("page  pages= %d, %d, %d, %d",cur_page,start_page,end_page,num_pages)
      
#    if end_page==1:  #????
#      return ''
    links = []
    """    
    for i in range(start_page,end_page+1):
      links_item = {}
      links_item['index'] = i
      links_item['offset'] = (i-1) * self.pagesize
      links.append(links_item)
    """    

    pagelinks = {}
    pagelinks['item'] = links
    pagelinks['cur_page'] = cur_page
    if cur_page>1:
      pagelinks['prev'] = cur_page - 1
    else:
      pagelinks['prev'] = None
    
    if cur_page < end_page:
      pagelinks['next'] = cur_page + 1
    else:
      pagelinks['next'] = None
          
    output = '';
    output += ' | <a href="%s%s">第一页</a> ' % (self.url,start_page)
    if pagelinks['prev'] is not None:
      output += ' | <a href="%s%s">上一页</a> ' % (self.url,pagelinks['prev'])
    else:
      output += ' | 上一页'
    """
    for i in pagelinks['item']:
      if i['index'] != pagelinks['cur_page']:
        output += '<a href="%s%s">%s</a> ' % (self.url,i['offset'],i['index'])
      else:
        output += ' %s ' % (i['index'])
    """
    if pagelinks['next'] is not None:
      output += ' | <a href="%s%s">下一页</a> ' % (self.url,pagelinks['next'])
    else:
      output += ' | 下一页'
    output += ' | <a href="%s%s">最末页</a>  | ' % (self.url,end_page)
    return output
    
    

    
